<template>
	<view id="bottom" class="bottom">
		<view class="input">
			<!-- 录制语音按钮 -->
			<view class="img img-voice" @tap="voiceBtnShow"></view>
			<view class="input-form" :style="{width:'calc(100% - '+(textContent?296:224)+'rpx)'}">
				<scroll-view v-if="voiceShow" scroll-y="true" class="scrollViewClass" @touchend.prevent="tapInput"
					@scroll="whenScroll">
					<!-- <view class=""> -->
					<view class="inputTextClass" :class="{'cursorAnimation':cursorIndex===-1}"
						style="width: 2px;height: 100%;"></view>
					<block v-for="(item,index) in contentArr" :key="index">
						<view v-if="item.type==='emoji'" @touchend.stop.prevent="tapContent(index)"
							class="inputEmojiClass" :class="cursorIndex===index?'cursorAnimation':''"
							:style="{ backgroundImage: 'url('+item.content.img+')'}"></view>
						<view v-if="item.type==='text'" @touchend.stop.prevent="tapContent(index)"
							class="inputTextClass" :class="cursorIndex===index?'cursorAnimation':''">
							{{item.content}}
						</view>
					</block>
					<!-- </view> -->
				</scroll-view>
				<button v-if="!voiceShow" class="btn-voice" style="width: 100%;" @touchstart="onRecordStart"
					@touchend="onRecordEnd">按住录音</button>
			</view>
			<view class="img img-smile" @tap="showModal" data-target="Emoji"></view>
			<view v-if="!textContent" class="img img-more" @tap="showModal" data-target="Func"></view>
			<button class="btn-send" :class="textContent?'slideright':'slideleft'" @tap="sendTextMessage">发送</button>

			<view style="height: 0;bottom:0;position: fixed;width: 100%;">
				<textarea :adjust-position="false" :show-confirm-bar="false" :hold-keyboard="true"
					:focus="messageInputFocusFlag" v-model="textContent" :cursor="cursorIndex+1"
					placeholder="隐藏该组件,只为能弹出软键盘" @focus="messageInputFocus" @blur="messageInputBlur"
					maxlength="2000"></textarea>
			</view>
		</view>
		<prompt-bottom :pheight="pheight" :mode="pMode"></prompt-bottom>
	</view>
</template>

<script>
	import promptBottom from '../prompt-bottom/prompt-bottom.vue'
	import {
		bus
	} from '../../../../../main.js'
	const recorderManager = uni.getRecorderManager();
	export default {
		props: {},
		components: {
			promptBottom
		},
		data() {
			return {
				//录音显示的按钮
				voiceShow: true,
				cursorIndex: -1,
				contentArr: [],
				textContent: '',
				messageInputFocusFlag: false,
				audio: {
					//语音录音中
					recording: false,
					//录音按钮展示
					visible: false,
					// 录音时长
					duration: 0,
					//周期调用
					timer: null
				},
				pheight: 0,
				pMode: '',
				timer: null,
				isScroll: false,
			}
		},
		watch: {
			textContent(newVel, oldVal) {
				console.log('这是监听textContent', newVel, oldVal, this.cursorIndex)
				// 如果没有取得焦点,说明正在点击表情,不参与下方程序
				if (this.messageInputFocusFlag) {
					// 当不是按顺序输入的时候,需要根据光标截取出需要的字符串
					// 如果是大于,说明是输入,否则是退格
					let tmp_newVal = newVel,
						tmp_oldVal = oldVal ? oldVal : '';
					if (tmp_newVal.length > tmp_oldVal.length) {
						let tmp_oldVal1 = tmp_oldVal ? tmp_oldVal.substr(0, this.cursorIndex + 1) : ''
						let tmp_oldVal2 = tmp_oldVal ? tmp_oldVal.substr(this.cursorIndex + 1, tmp_oldVal.length - 1) : ''

						let tmp_value = tmp_newVal.replace(tmp_oldVal1, '').replace(tmp_oldVal2, '')
						let tmp_valueArr = tmp_value.split('')
						const _this = this
						tmp_valueArr.forEach(item => {
							let tmp_item = {
									type: 'text',
									content: item
								}
								++_this.cursorIndex
							_this.contentArr.splice(_this.cursorIndex, 0, tmp_item)
						})
					} else {
						for (let i = 0; i < tmp_oldVal.length - tmp_newVal.length; i++) {
							this.contentArr.splice(this.cursorIndex, 1)
							this.cursorIndex--
						}
					}
				}
			},
			pheight(nVal, oVal) {
				this.getBottomHeight()
			}
		},
		created() {
			this.initRecorderListeners()

			// 获取底部bar的高度
			this.getBottomHeight()

			// 监听输入框的高度
			const _this = this
			uni.onKeyboardHeightChange(function(res) {
				console.log('监听输入框的高度', res);
				if (_this.pMode) {
					return
				}
				_this.pheight = res.height
			})

			bus.$on('updateInput', val => {
				if (val.mode === 'add') {
					this.cursorIndex += 1
					this.contentArr.splice(this.cursorIndex, 0, {
						type: 'emoji',
						content: val.content
					})
					this.textContent = !this.cursorIndex ? '替' :
						this.textContent.slice(0, this.cursorIndex) + '替' + this.textContent.slice(this
							.cursorIndex)
				} else if (val.mode === 'del') {
					if (this.cursorIndex > -1) {
						this.contentArr.splice(this.cursorIndex, 1)
						this.textContent = this.textContent.slice(0, this.cursorIndex) +
							this.textContent.slice(this.cursorIndex + 1)
						this.cursorIndex -= 1
					}
				}
			})

			// 点击屏幕时
			bus.$on('updateInputStatus', val => {
				if (val === 'promptHide') {
					this.hideModal()
				}
			})
		},
		beforeDestroy() {
			uni.offKeyboardHeightChange()
			bus.$off('updateInput')
			bus.$off('updateInputStatus')
		},
		methods: {
			getBottomHeight() {
				const _this = this;
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(function() {
					query.select('#bottom').boundingClientRect(data => {
						_this.bottom = data.height;

						bus.$emit('updateBottomH', data.height)
					}).exec();
				})
			},
			//显示录音按钮
			voiceBtnShow() {
				this.voiceShow = !this.voiceShow
				this.hideModal(1)
			},
			// 点击输入框的内容
			tapContent(index) {
				console.log('点击输入框的内容，isScroll=', this.isScroll);
				if (!this.isScroll) {
					console.log('没触发滑动，获取焦点');
					this.messageInputFocusFlag = true
					this.cursorIndex = index - 1
					this.hideModal()
				} else {
					console.log('删除滑动标记');
					this.isScroll = false

					if (this.timer) {
						console.log('关闭Interval');
						clearInterval(this.timer)
						this.timer = null
					}
				}
			},
			// 点击输入框
			tapInput(e) {
				console.log('点击输入框，isScroll=', this.isScroll);
				if (!this.isScroll) {
					console.log('没触发滑动，获取焦点');
					this.messageInputFocusFlag = true
					this.cursorIndex = this.contentArr.length - 1
					this.hideModal()
				} else {
					console.log('删除滑动标记');
					this.isScroll = false

					if (this.timer) {
						console.log('关闭Interval');
						clearInterval(this.timer)
						this.timer = null
					}
				}
			},
			hideModal(option) {
				console.log('hideModal', this.pMode, this.messageInputFocusFlag);
				if (this.pMode && !this.messageInputFocusFlag) {
					this.pheight = 0
				}
				this.pMode = null;
			},
			showModal(e) {
				console.log('显示弹窗', e.currentTarget.dataset.target);
				let tmp_value = e.currentTarget.dataset.target;
				this.pheight = 192;

				if (tmp_value === 'Emoji' || tmp_value === 'Func') {
					this.pMode = tmp_value
					this.messageInputFocusFlag = false
					uni.hideKeyboard()
					// this.setInterval()
				}

				if (tmp_value === 'Keyboard') {
					this.pMode = null
					this.tapInput()
				}
			},
			sendTextMessage() {
				this.hideModal()
				bus.$emit('updateContent', {
					type: 'text',
					payload: {
						content: this.contentArr
					}
				})

				this.$nextTick(function() {
					//发送完成将对话框清空
					this.textContent = ''
					this.contentArr = []
					this.cursorIndex = -1
				})
			},
			//点击开始录音
			onRecordStart() {
				this.setInterval()

				try {
					uni.showLoading({
						title: '正在录音...'
					});
					recorderManager.start();
				} catch (e) {
					console.log('录音错误', e)
				}
			},
			onRecordEnd() {
				try {
					uni.hideLoading();
					recorderManager.stop();
				} catch (e) {
					console.log(e);
				}
			},
			initRecorderListeners() {
				// 监听录音开始
				recorderManager.onStart(() => {
					this.audio.recording = true;
				});

				//录音结束后，发送
				recorderManager.onStop(res => {
					this.audio.recording = false;
				});

				// 监听录音报错
				recorderManager.onError(function(res) {
					console.log('录音报错：', res);
				});
			},
			messageInputFocus(e) {
				console.log('获得焦点');
				this.messageInputFocusFlag = true
			},
			messageInputBlur(e) {
				console.log('失去焦点');
				this.messageInputFocusFlag = false
			},
			whenScroll() {
				this.isScroll = true
				this.setInterval()
			},
			setInterval() {
				if (!this.timer) {
					console.log('开启Interval');
					this.timer = setInterval(() => {
						uni.hideKeyboard()
					}, 20)
				}
			}
		}
	}
</script>

<style lang="scss">
	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #ffffff;
		z-index: 1024;

		.input {
			// height: 42px;
			padding-right: 10px;
			box-shadow: 0 -1px 3px rgba(0, 0, 0, .1);
			box-sizing: border-box;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.img {
				width: 48rpx;
				height: 48rpx;
				margin-left: 20rpx;
				background-size: 100% 100%;
			}

			.img-voice {
				background-image: url(../../../../../static/img/chat/voice-circle.png);
			}

			.img-smile {
				background-image: url(../../../../../static/img/chat/smile.png);
			}

			.img-keyboard {
				background-image: url(../../../../../static/img/chat/keyboard.png);
			}

			.scrollViewClass {
				position: relative;
				max-height: 184rpx;
			}

			.img-more {
				background-image: url(../../../../../static/img/chat/more-.png);
			}

			.input-form {
				width: calc(100% - 224rpx);
				min-height: 32px;
				max-height: 100px;
				margin: 5px 0 5px 20rpx;
				background-color: #f5f5f5;

				display: flex;
				justify-content: flex-start;
				align-items: center;
			}

			.btn-send {
				position: absolute;
				right: 20rpx;
				height: 30px;
				padding: 0;
				margin-left: 20rpx;
				background-color: #fbaaaa;
				color: #ffffff;
				font-size: 12px;
			}

			.btn-voice {
				// background-color: #8fc77e;
				// color: #ffffff;
				font-size: 12px;
			}
		}
	}

	.inputEmojiClass {
		/* position: absolute; */
		width: 42rpx;
		height: 42rpx;
		background-size: cover;
		background-color: transparent;

		font-variant: small-caps;
		margin: 0;
		padding: 0;
		display: inline-flex;
		text-align: center;
		justify-content: center;
		align-items: center;
		color: #ffffff;
		white-space: nowrap;
		position: relative;
		background-size: cover;
		background-position: center;
		vertical-align: middle;
	}

	.inputTextClass {
		font-size: 16px;
		font-variant: small-caps;
		margin: 0;
		padding: 0;
		text-align: center;
		white-space: nowrap;
		position: relative;
		background-size: cover;
		background-position: center;
		vertical-align: middle;

		display: inline-flex;
		justify-content: center;
		align-items: center;
	}

	.cursorAnimation::after {
		position: absolute;
		content: "";
		display: inline-block;
		width: 1.5px;
		height: 32rpx;
		top: 50%;
		right: 0;
		transform: translateY(-50%);
		animation: blink 1s infinite steps(1, start);
	}

	@keyframes blink {

		0%,
		100% {
			background-color: #bb0808;
		}

		50% {
			background-color: transparent;
		}
	}

	.slideleft {
		width: 0;
		transition: all 0.1s;
	}

	.slideright {
		width: 120rpx;
		transition: all 0.25s;
	}
</style>
